package at.playbox.server.endpoints;

import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingType;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.ws.http.HTTPException;

import at.playbox.server.businesslogic.AuthenticationService;
import at.playbox.server.businesslogic.ShopService;

@WebServiceProvider
@BindingType(value = HTTPBinding.HTTP_BINDING)
public class BuySong implements Provider<Source>
{

	@Resource
	protected WebServiceContext wsContext;

	@SuppressWarnings("unchecked")
	public Source invoke(Source source)
	{
		try
		{
			MessageContext mc = wsContext.getMessageContext();
			HttpServletRequest request = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
			AuthenticationService authService = new AuthenticationService();
			if (authService.isAuthenticated(request))
			{
				System.out.println(authService.getUsername());
				Map<String, String> parameters = request.getParameterMap();
				if (parameters.containsKey("id"))
				{
					String requestId = request.getParameter("id");
					int id = Integer.parseInt(requestId);
					ShopService service = new ShopService();
					String result = service.createXML(service.buySong(id, authService.getUsername()));
					return new StreamSource(new ByteArrayInputStream(result.getBytes()));
				}
				else
				{
					throw new HTTPException(404);
				}
			}
			else
			{
				throw new RuntimeException("authentication is needed");
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new HTTPException(500);
		}
	}
}
